package com.dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.enums.JokeName;
import com.enums.JokeState;
import com.service.JokeManager;

/* Mettre toutes les methode a appeler par un jock */
public abstract class Joke extends Thread {
	protected List<Task> tasks;
	protected Task task;
	protected Iterator<Task> itrerator;
	protected JokeName joke_name;
	public JokeState joke_state = JokeState.WAITING; // son Etat avant Instanciant Wait : inutile mais symbolique

	public JokeState getJoke_state() {
		return joke_state;
	}

	public void setJoke_state(JokeState jokeState) {
		joke_state = jokeState;
	}

	public Joke() {
		super();
		tasks = new ArrayList<Task>();
		joke_state = JokeState.RUNNABLE;// au moment ou on instancie un joke son state devient RUNNABLE

	}

	private boolean firstTask = true;
	private boolean lastTask = false;

	/**
	 * On met ici le metier de chaque joke
	 * */
	@Override
	public final void run() { // TODO code qui neccssite d'etre optimiser

		if (firstTask && itrerator.hasNext()) {
			task = (Task) itrerator.next();
			JokeManager.serviceHandler.postDelayed(this,
					task.getStart_time() * 1000);
		} else if (task != null) {
			task.Start();
			if (!itrerator.hasNext())
				lastTask = true;
		}
		if (lastTask) {
			joke_state = JokeState.TERMINATED;
			JokeManager.serviceHandler.postDelayed(JokeManager.jokesFactory
					.getNextJoke(this), 1000L);
		} else if (!firstTask && itrerator.hasNext()) {
			task = (Task) itrerator.next();
			JokeManager.serviceHandler.postDelayed(this,
					task.getStart_time() * 1000);
		}
		firstTask = false;
	}
}
